using Microsoft.AspNetCore.Http;
using System.Text;
using System.Threading.Tasks;

namespace ST.Core.WEB
{
    public class MyMiddle
    {
       
        

        private readonly RequestDelegate _next;

        public MyMiddle(RequestDelegate next)
        {
            _next = next;
        }

        public async Task InvokeAsync(HttpContext context)
        {
            

            // 请求处理前逻辑
            // 例如：记录请求信息
            var requestPath = context.Request.Path;
            var requestMethod = context.Request.Method;


            // 保存原始的响应体流
            var originalBodyStream = context.Response.Body;
            try
            {
                // 创建一个新的内存流来存储响应内容
                using (var memoryStream = new System.IO.MemoryStream())
                {
                    // 将响应体设置为新的内存流
                    context.Response.Body = memoryStream;

                    // 调用下一个中间件
                    await _next(context);

                    if (context.Response.StatusCode == 404)
                    {
                        var r = new ApiResult<string> { Code = "404", Message = "资源未找到", Data = "" };
                        var s = ST.Core.Util.JSON.SerializeObject(r);
                        context.Response.ContentType = "application/json; charset=utf-8";
                        await originalBodyStream.WriteAsync(Encoding.UTF8.GetBytes(s));
                    }
                    // 检查响应状态码是否为成功状态且内容类型是否为JSON
                    else if (context.Response.StatusCode >= 200 && context.Response.StatusCode < 300)
                    {
                        if (context.Response.ContentType != null && context.Response.ContentType.Contains("application/json"))
                        {
                            // 将内存流的位置重置为开头
                            memoryStream.Position = 0;

                            // 读取内存流中的JSON数据
                            using (var streamReader = new System.IO.StreamReader(memoryStream))
                            {
                                var json = await streamReader.ReadToEndAsync();

                                var s = "";
                                // 解析JSON数据
                                var jo = Newtonsoft.Json.Linq.JToken.Parse(json);
                                var jor = new Newtonsoft.Json.Linq.JObject();
                                if (jo is Newtonsoft.Json.Linq.JObject && jo["Code"] != null)
                                {
                                    //已经是标准格式
                                    s = Util.JSON.SerializeObject(jo);
                                }
                                else
                                {
                                    jor["Code"] = "";
                                    jor["Message"] = "";
                                    jor["Data"] = jo;
                                    s = Util.JSON.SerializeObject(jor);
                                }


                                // 清空原始响应体
                                context.Response.Body = originalBodyStream;
                                context.Response.ContentLength = null;


                                // 将格式化后的JSON数据写入响应体                    
                                await context.Response.WriteAsync(s);
                            }
                        }
                        else
                        {
                            // 如果不满足条件，将内存流中的内容复制回原始响应体
                            memoryStream.Position = 0;
                            await memoryStream.CopyToAsync(originalBodyStream);
                           
                        }
                    }
                    else
                    {

                        // 如果不满足条件，将内存流中的内容复制回原始响应体
                        memoryStream.Position = 0;
                        await memoryStream.CopyToAsync(originalBodyStream);

                        //memoryStream.Position = 0;
                        //var buff = new byte[memoryStream.Length];
                        //var str = Encoding.ASCII.GetString(buff,0,buff.Length);
                        //var r = new ApiResult<string>
                        //{
                        //    Code = context.Response.StatusCode.ToString(),
                        //    Message = "系统异常",
                        //    Data = str
                        //};
                        //var s = ST.Core.Util.JSON.SerializeObject(r);
                        //await originalBodyStream.WriteAsync(Encoding.UTF8.GetBytes(s));
                    }
                }

            }
            catch (Exception ex)
            {
                string s = "";
                if (ex is ST.Core.MyException)
                {
                    var r = new ApiResult<string> { Code = "99", Message = ex.Message ?? "", Data = "" };
                    s = ST.Core.Util.JSON.SerializeObject(r);
                }
                else if (context.Response.StatusCode == 404)
                {
                    var r = new ApiResult<string> { Code = "404", Message = "资源未找到", Data = "" };
                    s = ST.Core.Util.JSON.SerializeObject(r);
                    context.Response.StatusCode = 404;
                }
                else
                {
                    var r = new ApiResult<string> { Code = "98", Message = "系统错误", Data = ex.Message };
                    s = ST.Core.Util.JSON.SerializeObject(r);
                    context.Response.StatusCode = 200;
                }
                context.Response.ContentType = "application/json";
                await originalBodyStream.WriteAsync(Encoding.UTF8.GetBytes(s));
            }
            finally
            {
                // 恢复原始的响应体流
                context.Response.Body = originalBodyStream;
            }

            // 请求处理后逻辑
            // 例如：记录响应状态码
            var responseStatusCode = context.Response.StatusCode;
        }
    }
}
